using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Logic;
using System.Collections.Generic;

namespace IQIGame.Onigao.GamePlay
{
    public class MainCityServiceManager : IReusableClass
    {
        private Dictionary<MainCityTriggerType, List<ServiceNonLevel>> _serviceTypeMap = new();

        public uint MaxStore => 50;

        public void Init(TViewEntity host, MainCityDynParamService serviceParam)
        {
            for (int i = 0; i < serviceParam.services.Count; i++)
            {
                var cfg = serviceParam.services[i];
                var service = ServiceNonLevel.Create(host, cfg, i);
                var triggerType = (MainCityTriggerType)service.trigger.type;
                List<ServiceNonLevel> services = null;
                if (!_serviceTypeMap.TryGetValue(triggerType, out services))
                {
                    services = new();
                    _serviceTypeMap.Add(triggerType, services);
                }
                services.Add(service);
            }
        }

        /// <summary>
        /// 触发服务
        /// </summary>
        /// <param name="triggerType">触发器类型</param>
        /// <param name="dynamicObjParam">引用类型通用动态参数</param>
        /// <param name="dynamicValueTypePram">值类型通用动态参数</param>
        /// <param name="triggeredService">是否有执行被运行</param>
        /// <returns>成功触发的服务</returns>
        public ServiceNonLevel TryTrigger(MainCityTriggerType triggerType, out bool anyExecDone, object dynamicObjParam, TrigValueTypeParam dynamicValueTypePram)
        {
            anyExecDone = false;
            ServiceNonLevel triggeredService = null;
            if (_serviceTypeMap.TryGetValue(triggerType, out var list))
            {
                foreach (var service in list)
                {
                    if (service.Trigger(dynamicObjParam, dynamicValueTypePram))
                    {
                        triggeredService = service;
                        anyExecDone = service.Execute() > 0;
                        //同一个类型同一时间只能触发一个服务，一旦触发成功就break
                        //该服务包含了一个不和其他服务重复（类型或参数有区别）的触发器和一堆包含条件的服务单元
                        //注意这里服务的定义和灵魂潮汐1不一样，该定义更上层，灵魂潮汐1的服务定义更像是这里的服务单元
                        break;
                    }
                }
            }
            return triggeredService;
        }

        public void OnReset()
        {
            foreach (var kv in _serviceTypeMap)
            {
                foreach (var service in kv.Value)
                {
                    service.Put2Pool();
                }
                kv.Value.Clear();
            }
            _serviceTypeMap.Clear();
        }
    }
}
